package com.maoxx.libms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.PageInfo;
import com.maoxx.libms.entity.Book;
import com.maoxx.libms.service.IBookService;
import com.maoxx.libms.vo.Result;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-10-25
 */
@Controller
@RequestMapping("/book")
@Slf4j
public class BookController {

    @Autowired
    private IBookService bookService;

    @RequestMapping("/view")
    public String view() {
        return "page/book";
    }




    /**
     * 分页查询
     * @param page 当前页
     * @param pageSize 每页显示条数
     * @param status 书籍状态
     * @return 分页列表
     */
    @GetMapping("/page")
    @ResponseBody
    public Result<PageInfo<Book>> page(Integer page, Integer pageSize, Character status) {
        log.info("--------------------------page:{},pageSize:{},status:{}", page, pageSize, status);
        PageInfo<Book> pageInfo = bookService.findBookPage(page, pageSize, status);
        return Result.success(pageInfo);
    }

    @PutMapping()
    @ResponseBody
    public Result<String> update(@RequestBody Book book) {
        boolean flag = bookService.update(book, new QueryWrapper<Book>().eq("book_id", book.getBookId()));
        if (!flag) {
            return Result.error("更新失败");
        }
        return Result.success("更新成功");
    }

    /**
     * 根据图书ID查询图书信息
     *
     * @param id 图书ID
     * @return 返回查询出来的图书信息
     */
    @GetMapping("/{id}")
    @ResponseBody
    public Result<Book> get(@PathVariable Integer id) {
        if (id != null) {
            Book book = bookService.getById(id);
            return Result.success(book);
        }
        return Result.error("查询失败");
    }

    @PostMapping()
    @ResponseBody
    public Result<String> add(@RequestBody Book book) {
        if (book == null) {
            return Result.error("添加失败");
        }
        boolean flag = bookService.save(book);
        return flag ? Result.success("添加成功") : Result.error("添加失败");
    }


}
